package com.lemlin.network

import com.blankj.utilcode.util.LogUtils
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

abstract class HttpServiceManager<ApiService : HttpServiceApi>(apiServiceClass: Class<ApiService>) {

    protected val apiService: ApiService =
        HttpServiceFactory.create(apiServiceClass, "http://topmall.icarefz.cn")

    /**
     * 在子线程加载数据
     */
    private fun <HttpData : HttpServiceData> observeOnMain(): ObservableTransformer<HttpData, HttpData> {
        return ObservableTransformer { upstream: Observable<HttpData> ->
            upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        }
    }

    /**
     * 网络加载数据观察
     */
    protected fun <HttpData : HttpServiceData> subscribe(
        observable: Observable<HttpData>,
        subscribe: HttpServiceSubscribe<HttpData>
    ): Disposable {
        return observable.doOnSubscribe {
            subscribe.onStart()
        }
            .compose(observeOnMain<HttpData>())
            .subscribe({
                subscribe.onSuccess(it)
            }, {
                subscribe.onFailure(it)
            })
    }
}